package Util::UserUser::UserUser;
use Moose;
use namespace::autoclean;
use JSON;

has 'schema' => (
	is => 'rw',
	required => 1,
	isa => 'DBIx::Class::Schema',
);

#####################################################
#Input: 
#	me_id
#	friend_id 
#Return: 
#	usersusers	
#####################################################
sub useruser_search {
	my ($self, $me_id, $friend_id, $status) = @_;

	unless(defined($status)) {
		return $self->schema->resultset('UserUser')->search({me_id => $me_id, friend_id => $friend_id }, {});
	} else {
		return $self->schema->resultset('UserUser')->search(
			{me_id => $me_id, 
			status => $status, 
			friend_id => $friend_id }, 
		{});
	}

}

#####################################################
#Input: 
#	me_id
#	friend_id 
#####################################################
sub accept_friends {
	my ($self, $me_id, $friend_id) = @_;
	my @me_users= $self->useruser_search($me_id, $friend_id);
        $me_users[0]->update({status => 'Y'});
	my @friend_users= $self->useruser_search($friend_id, $me_id);
        $friend_users[0]->update({status => 'Y'});
}

#####################################################
#Input: 
#	me_id
#	friend_id 
#####################################################
sub refuse_friends {
	my ($self, $me_id, $friend_id) = @_;
	my @me_users= $self->useruser_search($me_id, $friend_id);
	unless(scalar(@me_users) == 0) {
		$me_users[0]->delete;
	}
	my @friend_users= $self->useruser_search($friend_id, $me_id);
	unless(scalar(@friend_users) == 0) {
		$friend_users[0]->delete;
	}
}

#####################################################
#Input: 
#	me_id
#	friend_id 
#####################################################
sub add_to_users_users {
	my ($self, $me_id, $friend_id) = @_;
	my $me_user =  $self->schema->resultset('User')->find($me_id);
        my $friend_user =  $self->schema->resultset('User')->find($friend_id);

        $me_user->add_to_users_users({me_id=>$me_id, friend_id=>$friend_id, status=>"R"});
        $friend_user->add_to_users_users({me_id=>$friend_id, friend_id=>$me_id, status=>"A"});
}

__PACKAGE__->meta->make_immutable;

1;
